package com.sky.module.system.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.module.system.file.service.FileService;
import com.sky.module.system.user.dao.UserMapper;
import com.sky.module.system.user.domain.entity.User;
import com.sky.module.system.user.domain.vo.UserQueryVo;
import com.sky.module.system.user.service.UserService;
import com.sky.utils.SystemConstants;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zsg
 * @since 2023-02-20
 */
@Transactional
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Resource
    private FileService fileService;

    @Override
    public User findUserByUserName1(String username) {
        final LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public IPage<User> findUserListByPage(IPage<User> page, UserQueryVo userQueryVo) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!ObjectUtils.isEmpty(userQueryVo.getDepartmentId()), User::getDepartmentId, userQueryVo.getDepartmentId());
        queryWrapper.like(!ObjectUtils.isEmpty(userQueryVo.getUsername()), User::getUsername, userQueryVo.getUsername());
        queryWrapper.like(!ObjectUtils.isEmpty(userQueryVo.getRealName()), User::getRealName, userQueryVo.getRealName());
        queryWrapper.like(!ObjectUtils.isEmpty(userQueryVo.getPhone()), User::getPhone, userQueryVo.getPhone());
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public boolean deleteById(Long userId) {
        User user = baseMapper.selectById(userId);

        baseMapper.deleteUserRole(userId);

        if (baseMapper.deleteById(userId) > 0) {

            if (user != null && !ObjectUtils.isEmpty(user.getAvatar()) && !user.getAvatar().equals(SystemConstants.DEFAULT_AVATAR)) {
                {
//                    TODO 删除头像文件， 将阿里云改成基于s3 协议
//                    fileService.deleteFile(user.getAvatar());
                }
                return true;
            }
        }
        return true;
    }

    /***
     * @description 保存用户角色关联信息
     * @param userId
     * @param roleIds
     * @return boolean
     * @date 2023/2/24 10:48
     *
     */
    @Override
    public boolean saveUserRole(Long userId, List<Long> roleIds) {
        baseMapper.deleteById(userId);
        return baseMapper.saveUserRole(userId, roleIds) > 0;
    }
}
